package main

import (
	"fmt"
	"log"
	"os"

	"github.com/spf13/cast"
	"github.com/xuri/excelize/v2"
)

func main() {
	args := os.Args[1:]

	if len(args) != 2 {

		log.Println("Usage: ./export_excel_images.exe <file> <sheet index>")
		log.Println("Example: ./export_excel_images.exe test.xlsx 0")

		return
	}

	filePath := args[0]
	sheetIndex := cast.ToInt(args[1])

	f, err := excelize.OpenFile(filePath)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() {
		if err := f.Close(); err != nil {
			fmt.Println(err)
		}
	}()

	sheetName := f.GetSheetName(sheetIndex)

	for row := 1; row <= 500; row++ {
		for col := 1; col <= 20; col++ {
			cell, _ := excelize.CoordinatesToCellName(col, row)

			pics, err := f.GetPictures(sheetName, cell)
			if err != nil {
				fmt.Println(err)
			}
			for idx, pic := range pics {
				name := fmt.Sprintf("sheet%d-row%d-col%d-%d%s", sheetIndex, row, col, idx+1, pic.Extension)
				log.Println(name)
				if err := os.WriteFile(name, pic.File, 0644); err != nil {
					fmt.Println(err)
				}
			}
		}
	}
}
